{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "29b3f948-cc6a-4776-ad75-1dc259e0c298",
   "metadata": {},
   "source": [
    "# Bernstein-Vazirani Algorithm\n",
    "\n",
    "The Bernstein-Vazirani (BV) algorithm demonstrates an exponential speedup over classical methods for the particular task: \n",
    "\n",
    "Suppose we have an oracle that implements the function $f: \\{0,1\\}^n \\longrightarrow \\{0,1\\}$. \n",
    "\n",
    "$f(x)$ is promised to be the dot product between $x$ and a secret $n$-bit binary string $s$:\n",
    "\n",
    "$f(x) = x \\cdot s (mod \\space 2) =  (x_1s_1 + x_2s_2 + ... + x_ns_n) (mod \\space 2)$.\n",
    "\n",
    "Our goal is to find the secret string $s$.\n",
    "\n",
    "### Classical case\n",
    "\n",
    "For the case of $n=3$ consider $s=101$, which is a secret string and hence we dont have access to it. \n",
    "\n",
    "We have access to the function: $f(x) = x\\cdot s (mod \\space 2) = (x_1s_1 + x_2s_2 + x_3s_3) (mod \\space 2)$\n",
    "\n",
    "Let us strategically query the function to determine $s$. \n",
    "\n",
    "$1^{st}$ query: $f(001) = 001 \\cdot s (mod \\space 2) = (0 \\cdot 1 + 0 \\cdot 0 + 1 \\cdot 1)(mod \\space 2) = 1 (mod \\space 2) = 1$\n",
    "\n",
    "$2^{nd}$ query: $f(010) = 010 \\cdot s (mod \\space 2) = (0 \\cdot 1 + 1 \\cdot 0 + 0 \\cdot 1)(mod \\space 2) = 0 (mod \\space 2) = 0$\n",
    "\n",
    "$3^{rd}$ query: $f(100) = 100 \\cdot s (mod \\space 2) = (1 \\cdot 1 + 0 \\cdot 0 + 0 \\cdot 1)(mod \\space 2) = 1 (mod \\space 2) = 1$\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "Remember that from a user perspective, you only see $f(001) = 1$ since the inner mechanisms of the oracle and the value of $s$ is hidden from you. \n",
    "\n",
    "Why did we query $f(001)$ and not $f(011)$?\n",
    "\n",
    "For $f(001) = (x_1s_1 + x_2s_2 + x_3s_3) (mod \\space 2) = (0 + 0 + x_3s_3) (mod \\space 2) = (x_3s_3) (mod \\space 2) = 1 \\cdot s_3 (mod \\space 2) = s_3 (mod \\space 2) = 1$\n",
    "\n",
    "We have now isolated $s_3$ and know that $s_3 (mod \\space 2) = 1$. $s_3$ can only be 0 or 1 and in this case it has to be $1$ since $0 (mod \\space 2) = 0$. \n",
    "\n",
    "For $f(011) = (x_2s_2 + x_3s_3) (mod \\space 2)$, we will be left with $s_2$ and $s_3$ each of which will be more difficult to isolate via a combination of linear equations. Hence why we have to strategically query the function. \n",
    "\n",
    "In the classical case, we see that the secret string $s$ can be calculated in 3 queries. More generally speaking, it would take $n$ queries to generate enough information to determine $s$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ebdfe818",
   "metadata": {},
   "source": [
    "### Quantum case\n",
    "\n",
    "The BV quantum algorithm can take advantage of superposition and entanglement to encode the problem and produce an answer with a single oracle (black box function) query. The setup is a register of $n$ qubits in the $\\ket{0}$ state and a single auxiliary qubit in the $\\ket{1}$ state. The auxiliary qubit enables the phase kickback. Consider the register of $n$ qubits initialized here:\n",
    "\n",
    "$$ \\ket{0} $$\n",
    "\n",
    "Application of a Hadamard gate to each qubit results in:\n",
    "$$ H \\ket{0}  = \\frac{1}{\\sqrt{2^n}}\\sum_x^{n-1} \\ket{x}$$\n",
    "\n",
    "Next, the oracle, $U_f$, performs maps $\\ket{x}$ to $(-1)^{f(x)}\\ket{x}$ resulting in:\n",
    "\n",
    "$$ U_f \\frac{1}{\\sqrt{2^n}}\\sum_x^{n-1} \\ket{x} = \\frac{1}{\\sqrt{2^n}}\\sum_x^{n-1} (-1)^{f(x)}\\ket{x} =\\frac{1}{\\sqrt{2^n}}\\sum_x^{n-1} (-1)^{a*x}\\ket{x} $$\n",
    "\n",
    "Applying Hadamard gates again returns the following state:\n",
    "$$ H \\frac{1}{\\sqrt{2^n}}\\sum_x^{n-1} (-1)^{a*x}\\ket{x}  =  \\frac{1}{\\sqrt{2^n}}\\sum_{x,y}^{n-1} (-1)^{a*x} (-1)^{y*x} \\ket{y}  = \\frac{1}{\\sqrt{2^n}}\\sum_{y}^{n-1} \\sum_{x}^{n-1} (-1)^{(a \\oplus y)*x}\\ket{y} $$\n",
    "\n",
    "In the case of $a \\neq y$, the entire term becomes zero. In the case of $a = y$, the state $\\ket{a}$ is returned with an amplitude of 1.  This means there is a 100% chance of the measurement result being the hidden bitstring $a$ with only one call to the oracle!\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0fdbba1e-8eab-42a2-8964-6d7e86db0ad4",
   "metadata": {},
   "source": [
    "### Implementing in CUDA-Q\n",
    "\n",
    "The cell below generates a random bitstring of length $n$. If you are running this on your CPU, keep the qubit count small and increase to around 30 if you are running on a GPU with the `nvidia` backend."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "883762a1-d271-4692-adad-d64daa20805d",
   "metadata": {},
   "outputs": [],
   "source": [
    "import cudaq\n",
    "from typing import List\n",
    "\n",
    "cudaq.set_target('qpp-cpu')\n",
    "#cudaq.set_target('nvidia')  # GPU backend which enables scaling to large problem sizes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "d72225e6",
   "metadata": {},
   "outputs": [],
   "source": [
    "qubit_count = 5  # Set to around 30 qubits if you have GPU access\n",
    "\n",
    "secret_string = [1, 1, 0, 1,\n",
    "                 0]  # Change the secret string to whatever you prefer\n",
    "\n",
    "assert qubit_count == len(secret_string)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3df178fe-ccf3-41aa-b5f7-037a1a1d4a69",
   "metadata": {},
   "source": [
    "Next, the oracle kernel is defined. This will be used inside of the primary BV kernel, so it needs to take both the main register and auxiliary qubit as inputs as well as the secret bitstring. The oracle loops through the bits and applies a CNOT on the auxiliary qubit if the register qubit is a 1."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "91dbde75-486b-4015-9627-9ff404bdb475",
   "metadata": {},
   "outputs": [],
   "source": [
    "@cudaq.kernel\n",
    "def oracle(register: cudaq.qview, auxiliary_qubit: cudaq.qubit,\n",
    "           secret_string: List[int]):\n",
    "\n",
    "    for index, bit in enumerate(secret_string):\n",
    "        if bit == 1:\n",
    "            x.ctrl(register[index], auxiliary_qubit)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "685bb02e-afdc-4b69-afb4-81af9c2fafbd",
   "metadata": {},
   "source": [
    "The code below performs the steps described above for the BV algorithm, calling the oracle kernel as needed. You can see the circuit created below and verify that the procedure guessed the correct bitstring. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "d93cb1db-b5c6-45ef-9efc-c426895aac18",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     ╭───╮          ╭───╮          \n",
      "q0 : ┤ h ├───────●──┤ h ├──────────\n",
      "     ├───┤       │  ╰───╯╭───╮     \n",
      "q1 : ┤ h ├───────┼────●──┤ h ├─────\n",
      "     ├───┤       │    │  ├───┤     \n",
      "q2 : ┤ h ├───────┼────┼──┤ h ├─────\n",
      "     ├───┤       │    │  ╰───╯╭───╮\n",
      "q3 : ┤ h ├───────┼────┼────●──┤ h ├\n",
      "     ├───┤       │    │    │  ├───┤\n",
      "q4 : ┤ h ├───────┼────┼────┼──┤ h ├\n",
      "     ├───┤╭───╮╭─┴─╮╭─┴─╮╭─┴─╮╰───╯\n",
      "q5 : ┤ x ├┤ h ├┤ x ├┤ x ├┤ x ├─────\n",
      "     ╰───╯╰───╯╰───╯╰───╯╰───╯     \n",
      "\n",
      "secret bitstring = [1, 1, 0, 1, 0]\n",
      "measured state = 11010\n",
      "Were we successful? True\n"
     ]
    }
   ],
   "source": [
    "@cudaq.kernel\n",
    "def bernstein_vazirani(secret_string: List[int]):\n",
    "\n",
    "    qubits = cudaq.qvector(len(secret_string))  # register of size n\n",
    "    auxiliary_qubit = cudaq.qubit()  # auxiliary qubit\n",
    "\n",
    "    # Prepare the auxillary qubit.\n",
    "    x(auxiliary_qubit)\n",
    "    h(auxiliary_qubit)\n",
    "\n",
    "    # Place the rest of the register in a superposition state.\n",
    "    h(qubits)\n",
    "\n",
    "    # Query the oracle.\n",
    "    oracle(qubits, auxiliary_qubit, secret_string)\n",
    "\n",
    "    # Apply another set of Hadamards to the register.\n",
    "    h(qubits)\n",
    "\n",
    "    mz(qubits)  # measures only the main register\n",
    "\n",
    "\n",
    "print(cudaq.draw(bernstein_vazirani, secret_string))\n",
    "result = cudaq.sample(bernstein_vazirani, secret_string)\n",
    "\n",
    "print(f\"secret bitstring = {secret_string}\")\n",
    "print(f\"measured state = {result.most_probable()}\")\n",
    "print(\n",
    "    f\"Were we successful? {''.join([str(i) for i in secret_string]) == result.most_probable()}\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "388592de-3b47-45f4-b687-72abed6fdf8a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CUDA-Q Version latest (https://github.com/NVIDIA/cuda-quantum 176f1e7df8a58c2dc3d6b1b47bf7f63b4b8d3b63)\n"
     ]
    }
   ],
   "source": [
    "print(cudaq.__version__)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
